package com.link.base.base.message.push.service;

import com.link.base.base.message.push.model.PushInfo;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.RedisUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import com.meizu.push.sdk.server.IFlymePush;
import com.meizu.push.sdk.server.constant.ResultPack;
import com.meizu.push.sdk.server.model.push.PushResult;
import com.meizu.push.sdk.server.model.push.VarnishedMessage;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 魅族推送
 *
 * @author ouyangzhenqiang
 * @date 2019/08/12 16:12
 */
@Component
public class MeizuPushServiceImpl {
    
    /**
     * 推送消息
     * 
     * @author ouyangzhenqiang
     * @date 2019/08/12 16:12
     */
    void meizuPush(PushInfo record) throws Exception {
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            String redisKey = "APP_PUSH_CONFIG";
            String mzPushAppId = j.hget(redisKey,"mzPushAppId_" + record.getAppId());
            String mzPushAppSecret = j.hget(redisKey,"mzPushAppSecret_" + record.getAppId());
            LCLogger.info().withMessageKey("meizuPush").withMessage("mzPushAppId => "
                + mzPushAppId + ", mzPushAppSecret => " + mzPushAppSecret).flush();
            // 推送对象
            IFlymePush push = new IFlymePush(mzPushAppSecret);
            // 组装消息
            VarnishedMessage message = new VarnishedMessage.Builder().appId(Long.valueOf(mzPushAppId))
                .title(record.getPushTitle()).content(record.getPushNote()).build();
            // 目标用户
            List<String> pushIds = new ArrayList<String>();
            pushIds.add(record.getPushServiceToken());
            // 调用推送服务
            ResultPack<PushResult> result = push.pushMessage(message, pushIds);
            LCLogger.info().withMessageKey("meizuPush").withMessage("sendPush result => " + result).flush();
            if (result.isFailed()) {
                throw new BasicServiceException(result.comment());
            }
        } finally {
            RedisUtil.returnResource(j);
        }
    }
}
